#import "SMCircleViewController.h"
#import "SMMoment.h"
#import "SMComment.h"
#import "SMMomentCell.h"
#import "SMUserProfileViewController.h"


#import "SMTimeAgo.h"
#import <MJRefresh/MJRefresh.h>
#import "../../Managers/Network/SMAPIClient.h" // 关键：引入网络客户端

@interface SMCircleViewController ()<SMMomentCellDelegate>
@property(nonatomic, strong) NSMutableArray<SMMoment *> *data;
@property(nonatomic, assign) NSInteger page;
@property(nonatomic, assign) BOOL hasMore;
@end

@implementation SMCircleViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.title = @"圈子";
    [self.tableView registerClass:[SMMomentCell class] forCellReuseIdentifier:@"moment"];
    self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    self.tableView.backgroundColor = UIColor.systemGroupedBackgroundColor;

    self.data = [NSMutableArray array];
    self.page = 1; self.hasMore = YES;

    // MJRefresh
    self.tableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingTarget:self refreshingAction:@selector(refresh)];
    self.tableView.mj_footer = [MJRefreshAutoNormalFooter footerWithRefreshingTarget:self refreshingAction:@selector(loadMore)];
    [self.tableView.mj_header beginRefreshing];
}

#pragma mark - Refresh / LoadMore

- (void)refresh {
    self.page = 1;
    self.hasMore = YES;
    [self requestPage:self.page];
}

- (void)loadMore {
    if (self.hasMore) {
        self.page++;
        [self requestPage:self.page];
    } else {
        [self.tableView.mj_footer endRefreshingWithNoMoreData];
    }
}

#pragma mark - Network (with fallback mock)

- (void)requestPage:(NSInteger)page {
    NSDictionary *params = @{@"page": @(page), @"pageSize": @(10)};
    __weak typeof(self) weakSelf = self;

    [[SMAPIClient shared] GET:@"circle/list"
                   parameters:params
                      success:^(id json) {
        NSArray *arr = nil;
        if ([json isKindOfClass:[NSDictionary class]] && [json[@"data"] isKindOfClass:[NSArray class]]) {
            arr = json[@"data"];
        } else if ([json isKindOfClass:[NSArray class]]) {
            arr = (NSArray *)json;
        }
        if (!arr) { // 结构不符，走本地模拟
            [weakSelf applyData:[weakSelf mockPage:page] page:page];
            return;
        }

        NSMutableArray *parsed = [NSMutableArray array];
        for (NSDictionary *d in arr) {
            if (![d isKindOfClass:NSDictionary.class]) continue;
            SMMoment *m = [SMMoment new];
            m.momentId  = [NSString stringWithFormat:@"%@", d[@"id"] ?: [[NSUUID UUID] UUIDString]];
            m.author    = d[@"author"] ?: @"用户";
            m.avatarURL = d[@"avatar"] ?: @"";
            m.text      = d[@"text"] ?: @"";
            NSArray *imgs = d[@"images"];
            if ([imgs isKindOfClass:NSArray.class]) m.imageURLs = imgs;
            NSNumber *ts = d[@"created_at"]; // 支持秒/毫秒都行（SMTimeAgo里已兼容）
            if (ts) m.createdAt = [SMTimeAgo dateFromUnix:ts.doubleValue];
            m.likesCount = [d[@"likes"] integerValue];
            m.isLiked    = [d[@"is_liked"] boolValue];
            m.isExpanded = NO;

            // comments
            NSMutableArray *cmts = [NSMutableArray array];
            NSArray *cs = d[@"comments"];
            if ([cs isKindOfClass:NSArray.class]) {
                for (NSDictionary *cd in cs) {
                    SMComment *c = [SMComment new];
                    c.commentId = [NSString stringWithFormat:@"%@", cd[@"id"] ?: [[NSUUID UUID] UUIDString]];
                    c.author    = cd[@"author"] ?: @"匿名";
                    c.text      = cd[@"text"] ?: @"";
                    NSNumber *cts = cd[@"created_at"];
                    c.createdAt = cts ? [SMTimeAgo dateFromUnix:cts.doubleValue] : [NSDate date];
                    [cmts addObject:c];
                }
            }
            m.comments = cmts;
            [parsed addObject:m];
        }

        [weakSelf applyData:parsed page:page];

    } failure:^(NSError *error) {
        // 网络失败，回退本地模拟
        [weakSelf applyData:[weakSelf mockPage:page] page:page];
    }];
}

- (NSArray<SMMoment *> *)mockPage:(NSInteger)page {
    NSMutableArray *new = [NSMutableArray array];
    for (int i = 0; i < 10; i++) {
        SMMoment *m = [SMMoment new];
        m.momentId = [NSString stringWithFormat:@"%ld-%d",(long)page,i];
        m.author   = [NSString stringWithFormat:@"用户%d", arc4random_uniform(200)+1];
        m.avatarURL= [NSString stringWithFormat:@"https://i.pravatar.cc/100?img=%d", arc4random_uniform(70)+1];

        // 文本（偏长，便于测试“最多三行 + 展开”）
        m.text = [NSString stringWithFormat:@"第%ld页第%d条：这是一段较长的文案，用于测试三行折叠与展开。清新朋友圈动态示例，支持九宫格清新朋友圈动态示例，支持九宫格清新朋友圈动态示例，支持九宫格清新朋友圈动态示例，支持九宫格清新朋友圈动态示例，支持九宫格清新朋友圈动态示例，支持九宫格小清新朋友圈动态示例，支持九宫格、点赞、评论与相对时间。欢迎交流。",(long)page,i];

        // 1~9 张图
        int imgCount = (arc4random_uniform(9))+1;
        NSMutableArray *imgs = [NSMutableArray array];
        for(int k=0;k<imgCount;k++){
            [imgs addObject:[NSString stringWithFormat:@"https://picsum.photos/240/240?%d", arc4random_uniform(100000)]];
        }
        m.imageURLs = imgs;

        m.createdAt = [NSDate dateWithTimeIntervalSinceNow:-(arc4random_uniform(7*24*3600))];
        m.likesCount= arc4random_uniform(200);
        m.isLiked   = NO;
        m.isExpanded= NO;

        // 随机 0~3 条评论
        int cmt = arc4random_uniform(4);
        m.comments=[NSMutableArray array];
        for (int c=0;c<cmt;c++){
            SMComment *cm=[SMComment new];
            cm.commentId=[[NSUUID UUID] UUIDString];
            cm.author = [NSString stringWithFormat:@"评论者%d", arc4random_uniform(300)+1];
            cm.text   = (arc4random_uniform(2)==0) ? @"不错，继续加油！" : @"这个看起来很实用～";
            cm.createdAt = [NSDate date];
            [m.comments addObject:cm];
        }
        [new addObject:m];
    }
    return new;
}

- (void)applyData:(NSArray<SMMoment *> *)arr page:(NSInteger)page {
    if (page == 1) [self.data removeAllObjects];
    [self.data addObjectsFromArray:arr];
    self.hasMore = arr.count >= 10;

    [self.tableView reloadData];
    [self.tableView.mj_header endRefreshing];
    if (self.hasMore) {
        [self.tableView.mj_footer endRefreshing];
    } else {
        [self.tableView.mj_footer endRefreshingWithNoMoreData];
    }
}

#pragma mark - Table

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return self.data.count;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return [SMMomentCell heightForMoment:self.data[indexPath.row] width:UIScreen.mainScreen.bounds.size.width];
}

- (UITableViewCell*)tableView:(UITableView*)tv cellForRowAtIndexPath:(NSIndexPath*)ip {
    SMMomentCell *c = [tv dequeueReusableCellWithIdentifier:@"moment" forIndexPath:ip];
    [c configure:self.data[ip.row]];
    c.delegate = self;
    return c;
}

#pragma mark - SMMomentCellDelegate
- (void)momentCellDidTapAvatar:(NSString *)momentId {
    // 根据 momentId 找到该条动态的作者信息，然后跳转他人主页
    NSInteger row = [self.data indexOfObjectPassingTest:^BOOL(SMMoment * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        return [obj.momentId isEqualToString:momentId];
    }];
    if (row == NSNotFound) return;
    SMMoment *m = self.data[row];

    // 假设你有他人主页控制器
    SMUserProfileViewController *vc = [[SMUserProfileViewController alloc] initWithUserId:(m.author ?: m.author ?: @"")];
    vc.hidesBottomBarWhenPushed = YES;
    [self.navigationController pushViewController:vc animated:YES];
}

#pragma mark - SMMomentCellDelegate

- (void)momentCellDidToggleExpand:(NSString *)momentId{ NSInteger row = [self indexForMomentId:momentId]; if (row == NSNotFound) return; SMMoment *m = self.data[row]; m.isExpanded = !m.isExpanded; [self.tableView reloadRowsAtIndexPaths:@[[NSIndexPath indexPathForRow:row inSection:0]] withRowAnimation:UITableViewRowAnimationAutomatic]; }

- (void)momentCellDidTapLike:(NSString *)momentId {
    NSInteger row = [self indexForMomentId:momentId];
    if (row == NSNotFound) return;
    SMMoment *m = self.data[row];
    m.isLiked = !m.isLiked;
    m.likesCount += m.isLiked ? 1 : -1;
    [self.tableView reloadRowsAtIndexPaths:@[[NSIndexPath indexPathForRow:row inSection:0]]
                          withRowAnimation:UITableViewRowAnimationNone];
}

- (void)momentCellDidTapComment:(NSString *)momentId {
    // TODO: push 评论输入界面
}



#pragma mark - Helper

- (NSInteger)indexForMomentId:(NSString *)mid {
    __block NSInteger idx = NSNotFound;
    [self.data enumerateObjectsUsingBlock:^(SMMoment * _Nonnull obj, NSUInteger i, BOOL * _Nonnull stop) {
        if ([obj.momentId isEqualToString:mid]) { idx = i; *stop = YES; }
    }];
    return idx;
}

@end
